<template>
	<view>
		<el-container>
			<a-button class="buy-btn" v-show="buyStatus==false" @click="buy">立即续费</a-button>
			<a-button class="buy-btn" v-show="buyStatus==true" @click="changeStatus">上一步</a-button>
			
			<template v-if="codeUrl && status !== 2">
					
				<view class='pay-info'>
					
					<a-row>
						<a-col>
							<h3 style="text-align: center;">请使用微信扫码支付</h3>
						</a-col>
					</a-row>
					
					<canvas canvas-id="qrcode" style="width: 300px;height: 300px;" />
				
					<a-row type="flex" justify="center">
						<a-col :span="24">
								<a-button block type="primary" @click="orderQuery">我已完成支付</a-button>
						</a-col>
					</a-row>
				</view>
			 
			</template>
			
			<el-row v-show="buyStatus==false">
				<el-col :span="24">
					<h1>续费中心</h1>
				</el-col>
				<el-col :span="24">
					<el-descriptions title="机构信息"  v-if="meinfo">
						<el-descriptions-item label="机构名称">{{meinfo.name?meinfo.name:''}}</el-descriptions-item>
						<el-descriptions-item label="手机号">{{meinfo.mobile?meinfo.mobile:''}}</el-descriptions-item>
						<el-descriptions-item label="联系地址">{{meinfo.address?meinfo.address:''}}</el-descriptions-item>
						<el-descriptions-item label="备注">
							{{meinfo.note?meinfo.note:''}}
						</el-descriptions-item>
						<el-descriptions-item label="驾校状态">
							<el-row :gutter="4">
								<el-col :span="8">
									<uni-dateformat :date="meinfo.start_time?meinfo.start_time:0"></uni-dateformat>
								</el-col>
								<el-col :span="8">
									<uni-dateformat :date="meinfo.end_time?meinfo.end_time:0"></uni-dateformat>
								</el-col>
								<el-col :span="8">
									<el-tag>
										{{getMeStatusText}}
									</el-tag>
								</el-col>
							</el-row>
						</el-descriptions-item>

					</el-descriptions>
				</el-col>
			</el-row>
			<el-row v-show="buyStatus==true">
				<el-table :data="priceList" border style="width: 100%">
					<el-table-column prop="realFee" label="价格" width="180">
					</el-table-column>
					<el-table-column prop="day" label="有效期(天)" width="180">
					</el-table-column>
					<el-table-column fixed="right" label="操作" width="100">
						<template slot-scope="scope">
							<el-button @click="handleClick(scope.row)" type="text" size="small">立即购买</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-row>
		</el-container>
	</view>
</template>

<script>
	import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
	
	const db = uniCloud.database()
	const dbCmd = db.command
	export default {
		name: "OweBuy",
		props: {
			//机构ID
			meId:''
		},
		data() {
			return {
				runCount:0,
				ME_ID:'',
				times:10,
				startQueryTask:null,
				status: 0,
				statusText: ['未支付', '已支付'],
				codeUrl: '',
				outTradeNo: '',
				priceList: [],
				buyStatus: false,
				meinfo: null,
				loading: true,
				statusMap: [{
						"value": 0,
						"text": "欠费"
					},
					{
						"value": 1,
						"text": "正常"
					},
					{
						"value": 2,
						"text": "终止"
					}
				]
			}
		},
		computed: {
			getMeStatusText() {
				if (this.meinfo.hasOwnProperty('status')) {
					return this.statusMap[this.meinfo.status].text
				} else {
					return ''
				}
			}
		},
		watch:{
			// meId(nv){
			// 	if(nv!=''){
			// 		this.getMeInfo(nv)
			// 	}
			// }
		},
		methods: {

			pay() {
				const providerList = ['wxpay', 'alipay']
				let selectedProvider = ''
				new Promise((resolve, reject) => {
					resolve(providerList[0])
				}).then((provider) => {
					selectedProvider = provider
					return uniCloud.callFunction({
						name: 'pay',
						data: {
							provider,
							outTradeNo: this.outTradeNo
						}
					})
				}).then((res) => {
					console.log(res);
					this.codeUrl = res.result.orderInfo.codeUrl
					this.startQueryTask = setInterval(()=>{
						if(this.times>0){
							this.orderQuery()
							this.times--
						}else{
							clearInterval(this.startQueryTask)
						}
					},5000)
					uni.hideLoading()
					return uQRCode.make({
						canvasId: 'qrcode',
						componentInstance: this,
						text: this.codeUrl,
						size: 300,
						margin: 10,
						backgroundColor: '#ffffff',
						foregroundColor: '#000000',
						fileType: 'jpg',
						correctLevel: uQRCode.errorCorrectLevel.H
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '获取支付二维码失败',
						showCancel: false
					})
				})
			},
			order(id) {
				console.log('下单', id)
				const self = this
				return new Promise((resolve, reject) => {
					uniCloud.callFunction({
							name: 'order',
							data: {
								goodId: id
							}
						}).then((res) => {
							if (res.result.outTradeNo) {
								self.outTradeNo = res.result.outTradeNo
								resolve(res)
							} else {
								throw new Error(res.result.outTradeNo)
							}
						})
						.catch((err) => {
							uni.showModal({
								content: err.message || '下单失败',
								showCancel: false
							})
						})
				})
			},
			orderQuery() {
				const self = this 
				uniCloud.callFunction({
					name: 'order-query',
					data: {
						outTradeNo: this.outTradeNo
					}
				}).then((res) => {
					
					if(this.startQueryTask && res.result.orderPaid){
						clearInterval(this.startQueryTask)
					}
					
					if (res.result.orderPaid) {
						this.status = 2
						uni.showModal({
							content: '订单已支付',
							showCancel: false
						})
						self.getMeInfo(self.ME_ID)
					} 
					
					if(this.times<=0 && !res.result.orderPaid){
						uni.showModal({
							content: '订单未支付',
							showCancel: false
						})
					}
				}).catch((e) => {
					uni.showModal({
						content: '查询订单状态失败，请稍后再试',
						showCancel: false
					})
				})
			},

			changeStatus() {
				this.buyStatus = false
			},
			buy() {
				this.buyStatus = true
			},
			handleClick(row) {
				console.log(row)
				uni.showLoading({
					title:'加载中'
				})
				this.order(row._id).then(order => {
					console.log('下单号', order)
					this.pay(order)
				})
			},
			async getPricesList() {
				const data = await db.collection('price-list').orderBy('day desc').get();
				//	console.log('preics', data)
				this.priceList = data.result.data
			},
			async getMeInfo(meId) {
					console.log('meid=>', meId)
					console.log('RunCount',this.runCount++)
				let meinfo = await db.collection('mechanism').where({
					_id: dbCmd.eq(meId)
				}).limit(1).get()
				this.meinfo = meinfo.result.data[0]
				this.$set(this,'meinfo',meinfo.result.data[0])
				this.loading = false
				// this.$nextTick(()=>{
				// 	this.$forceUpdate()
				// })

			}
		},
		created() {
			this.ME_ID = this.meId
			this.getPricesList()
			this.getMeInfo(this.ME_ID)
		},
		mounted() {
				//this.getMeInfo(this.meId)
		}
	}
</script>

<style lang="scss" scoped>
	@import url('./owe.css');
</style>
